package com.example.demo;

import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author linjingze
 * @date 2023/11/23 11:02 上午
 */
public class ExcelUtils {

    public static void writeRow(XSSFSheet sheet, XSSFCellStyle cellStyle, List<BaseRowData> rowDataList) {
        Map<Integer, List<BaseRowData>> rowMap = rowDataList.stream().collect(Collectors.groupingBy(BaseRowData::getExRow));
        for (Map.Entry<Integer, List<BaseRowData>> e : rowMap.entrySet()) {
            Integer startRow = e.getKey();
            List<BaseRowData> headList = e.getValue();
            XSSFRow row = sheet.createRow(startRow);
            Short height = headList.get(0).getHeight();
            if (height != null) {
                row.setHeightInPoints(height);
            }
            XSSFDrawing d = sheet.createDrawingPatriarch();
            for (BaseRowData exHead : headList) {
                int exColumn = exHead.getExColumn();
                sheet.setColumnWidth(exColumn, 3500);
                XSSFCell cell = row.createCell(exColumn);
                if (exHead.needMergeColumn()) {
                    for (int i = 1; i <= exHead.getMergeColumn(); i++) {
                        row.createCell(exColumn + 1);
                    }
                    sheet.addMergedRegion(new CellRangeAddress(startRow,
                            startRow + exHead.getMergeRow(), exColumn, exColumn + exHead.getMergeColumn()));
                }
                if (exHead.needMergeRow()) {
                    sheet.addMergedRegion(new CellRangeAddress(startRow,
                            startRow + exHead.getMergeRow(), exColumn, exColumn + exHead.getMergeColumn()));
                }
                cell.setCellValue(exHead.getName());
                cell.setCellStyle(cellStyle);
            }
        }
    }
}
